package org.upupxjg.xlog;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.upupxjg.xlog.template.TemplateProcessor;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 * User: xiaojiangang
 * Date: 13-6-22
 * Time: 下午9:40
 */
public class CoreFilter implements Filter{

    private static final Logger LOGGER = LoggerFactory.getLogger(CoreFilter.class);

    //WebRoot/WEB-INF/template
    private static final String TEMPLATE_PATH = "template";
    private String templatePath = TEMPLATE_PATH;
    private TemplateProcessor templateProcessor;
    private static final String CONFIG_FILE = "xlog.properties";
    private String configFile = CONFIG_FILE;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String configFile = filterConfig.getInitParameter("config-file");
        if(null != configFile && !configFile.trim().isEmpty()){
            this.configFile = configFile;
        }
        // load configure
        Properties properties = new Properties();
        try {
            properties.load(new FileReader(new File(this.getClass().getClassLoader().getResource(configFile).getFile())));
            String tempPath = properties.getProperty("template_path");
            if (null !=  tempPath && !tempPath.trim().isEmpty()){
                templatePath = tempPath;
            }


        } catch (IOException e) {
            //TODO no configre file
            templatePath = TEMPLATE_PATH;
        }
        templatePath = filterConfig.getServletContext().getRealPath("WEB-INF/"+templatePath);
        LOGGER.info("SET TEMPLATE FILE PATH:["+templatePath+']');

        templateProcessor = new TemplateProcessor(templatePath);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String path = request.getServletPath();
        if (path.equals("") || path.equals("/")){
            path = "index.md";
        }
        if (path.endsWith(".html")||path.endsWith(".htm")){
            path = path.substring(0,path.lastIndexOf(".htm"))+".md";
        }
        if(templateProcessor.hasFile(path)){
            LOGGER.info("FIND template:["+path+"]");
            servletResponse.setContentType("text/html");
            servletResponse.setCharacterEncoding("utf8");
            servletResponse.getWriter().print(templateProcessor.getFileProcessed(path));
            servletResponse.getWriter().flush();
            servletResponse.getWriter().close();
            return;
        }else{
            LOGGER.info("CAN NOT FIND PATH:["+path+"]");
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    @Override
    public void destroy() {
        //To change body of implemented methods use File | Settings | File Templates.
    }
}
